package com.isaacwaller.digg;

import static com.isaacwaller.digg.DiggInterface.reportError;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

public class ListTopics extends ListActivity implements Runnable {

	private Handler handler = new Handler() {
	        public void handleMessage(Message msg) {
	        	setListAdapter((ListAdapter)msg.obj);
	        }
	    };
	    
	    public boolean onCreateOptionsMenu(Menu menu) {
	        boolean result = super.onCreateOptionsMenu(menu);
	        MenuInflater inflater = new MenuInflater(this);
	        inflater.inflate(R.menu.categoriestopics, menu);
	        menu.removeItem(R.id.topics);
	        
	        menu.findItem(R.id.categories).setIntent(new Intent(this, MainMenu.class));
	        return result;
	    }
	
	
	public void run() {
		try {
			Message m = new Message();
			m.obj = new DiggResponseListAdapter(this,"topics","topics","name");
			handler.sendMessage(m);
		} catch (ClientProtocolException e) {
			DiggInterface.reportError(e);
		} catch (URISyntaxException e) {
			reportError(e);
		} catch (IOException e) {
			reportError(e);
		} catch (JSONException e) {
			reportError(e);
		}
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new Thread(this).start();
    }
    
    protected void  onListItemClick  (ListView l, View v, int position, long id)  {
    	Intent i = new Intent(this,ListStories.class);
    	JSONObject j = (JSONObject) l.getAdapter().getItem(position);
    	try {
			i.putExtra("path", "topic/"+j.getString("short_name"));
			i.putExtra("display",j.getString("name"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
    	startActivity(i);
    }
}